<?php

/**
 * This is the model class for table "user".
 *
 * The followings are the available columns in table 'user':
 * @property string $userid
 * @property string $name
 * @property string $department
 * @property string $position
 * @property string $mobile
 * @property integer $gender
 * @property string $email
 * @property string $weixinid
 * @property string $avatar
 * @property integer $status
 * @property string $extattr
 */
class User extends Base
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'user';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('userid', 'required'),
			array('gender, status', 'numerical', 'integerOnly'=>true),
			array('userid, name', 'length', 'max'=>20),
			array('department', 'length', 'max'=>250),
			array('position', 'length', 'max'=>15),
			array('mobile', 'length', 'max'=>11),
			array('email, weixinid', 'length', 'max'=>25),
			array('avatar', 'length', 'max'=>150),
			array('extattr', 'length', 'max'=>300),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('userid, name, department, position, mobile, gender, email, weixinid, avatar, status, extattr', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'userid' => '成员UserID。对应管理端的帐号',
			'name' => '成员名称',
			'department' => '成员所属部门id列表',
			'position' => '职位信息',
			'mobile' => '手机号码。第三方仅通讯录套件可获取',
			'gender' => '性别。0表示未定义，1表示男性，2表示女性',
			'email' => '邮箱。第三方仅通讯录套件可获取',
			'weixinid' => '微信号',
			'avatar' => '头像url。注：如果要获取小图将url最后的"/0"改成"/64"即可',
			'status' => '关注状态: 1=已关注，2=已冻结，4=未关注',
			'extattr' => '扩展属性。第三方仅通讯录套件可获取',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('userid',$this->userid,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('department',$this->department,true);
		$criteria->compare('position',$this->position,true);
		$criteria->compare('mobile',$this->mobile,true);
		$criteria->compare('gender',$this->gender);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('weixinid',$this->weixinid,true);
		$criteria->compare('avatar',$this->avatar,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('extattr',$this->extattr,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	protected function pageListOpt(CDbCriteria $criteria) {
    }

    /**
     * 获取所有图片。并判断用户是否有这些图片权限
     * @param $page int 页码
     * @param $limit int 每页显示个数
     * @param $floder_id int 相册id
     * @return array 当前用户相片权限
    */
    public function getUserImg($page, $limit, $floder_id) {
        if (empty($this->userid) || empty($floder_id)) {
            return array();
        }

        $offset = ($page-1) * $limit;
        $user_img = $this->getDbConnection()->createCommand()
            ->select('a.id,a.thumb_src,a.title,b.userid')
            ->from('image a')
            ->leftJoin('user_img b','a.id=b.image_id')
            ->where('a.pid=:pid', array(':pid'=>$floder_id))
            ->offset($offset)
            ->group('a.id')
            ->limit($limit)
            ->queryAll();
        foreach ($user_img as $k => $img) {
            if ($img['userid'] == $this->userid) {
                $user_img[$k]['has'] = 0;
            } else {
                $user_img[$k]['has'] = 1;
            }
        }
        return array(
            'code' => 0,
            'messgae' => '查询成功',
            'data' => $user_img
        );
    }

    /**
     * 修改用户的图片权限
     * @param $img_id int 图片id
     * @param  $is_checked bool 是否有该图片权限
     * @param  $pid int 相册id
     * @return bool 是否修改成功
    */
    public function changeImg($img_id, $is_checked, $pid) {
        if (empty($this->userid)) {
            $this->addError('user', '用户不存在');
            return false;
        }
        if (empty($img_id) || !in_array($is_checked, array('0','1'))) {
            $this->addError('user', '参数非法');
            return false;
        }
        $transaction = $this->getDbConnection()->beginTransaction();
        $ret = $this->getDbConnection()->createCommand()->delete('user_img',
            'userid=:userid and image_id=:image_id',
            array(':image_id' => $img_id, ':userid' => $this->userid)
        );
        if ($ret === false) {
            $transaction->rollback();
            $this->addError('db', '数据删除失败');
            return false;
        }
        if (!$is_checked) {
            $data = array(
                'userid' => $this->userid,
                'image_id' => $img_id,
                'pid' => $pid
            );
            $ret = $this->getDbConnection()->createCommand()->insert('user_img', $data);
            if ($ret === false) {
                $transaction->rollback();
                $this->addError('db', '数据删除失败');
                return false;
            }
        }
        $transaction->commit();
        return true;
    }

    /**
     * 批量修改用户图片权限
     * @param $pid int 相册id
     * @param $checked bool 选择/取消
     * @param $userid string 用户id
    */
    public function batchChangeImg($pid,$checked,$userid) {
        if (empty($this->userid)) {
            $this->addError('img','用户不存在');
            return false;
        }
        if (empty($pid)) {
            $this->addError('img','参数非法');
            return false;
        }
        $image_list = Image::model()->findAll('pid=:pid',array(':pid'=>$pid));
        if (empty($image_list)) {
            return true;
        }
        $transaction = $this->getDbConnection()->beginTransaction();
        $ret = $this->getDbConnection()->createCommand()
            ->delete('user_img','pid=:pid and userid=:userid', array(':pid'=>$pid,':userid'=>$userid));
        if ($ret === false) {
            $transaction->rollback();
            $this->addError('img', '删除失败');
            return false;
        }

        if (!$checked) {
            $insert_data = array();
            foreach ($image_list as $image) {
                $insert_data[] = array(
                    'userid' => $this->userid,
                    'image_id' => $image->id,
                    'pid' => $pid
                );
            }
            $ret = $this->getDbConnection()->schema->commandBuilder
                ->createMultipleInsertCommand('user_img', $insert_data)
                ->execute();
            if ($ret === false) {
                $transaction->rollback();
                $this->addError('img', '插入失败');
                return false;
            }

        }
        $transaction->commit();
        return true;
    }


    /**
     * 显示微信端用户的所有图片
     * @param $params array 相关参数
     * @return array 用户所属图片
     */
    public function wechatUserImg($params) {
        if (empty($this->userid)) {
            return array();
        }
        $param_val = array(
            ':pid' => $params['pid'],
            ':userid' => $this->userid,
        );
        $join_table = '(select image_id from user_img where userid=:userid and pid=:pid)';
        $count_sql = "select count(1) as total from image a left join $join_table b on a.id=b.image_id where ";
        $data_where = 'a.pid=:pid and b.image_id is null';
        if (!empty($params['keyword'])) {
            $data_where .= ' and title like :title';
            $param_val[':title'] = $params['keyword'] . '%';
        }
        $count_sql .= $data_where;
        $total_ret = $this->getDbConnection()
            ->createCommand($count_sql)
            ->queryRow(true, $param_val); //获取总数
        $total = intval($total_ret['total']);
        $page = intval($params['page']);
        $limit = 10;  //每次加载个数
        $offset = ($page - 1) * $limit;  //偏移量
        $page_total = ceil($total / $limit);  //总页数

        $user_img = $this->getDbConnection()->createCommand()
            ->select('a.id,a.thumb_src,a.title,a.upload_src')
            ->from('image a')
            ->leftJoin("$join_table b",'a.id=b.image_id')
            ->where($data_where, $param_val)
            ->offset($offset)
            ->limit($limit)
            ->queryAll();
        return array(
            'page_total' => $page_total,
            'data' => $user_img
        );
    }

    /**
     * 拉取用户信息
    */
    public function downloadUser() {
        try {
            $api = new WechatApi();
        } catch (CException $e) {
            $this->addError('user', $e->getMessage());
            return false;
        }
        $user_ret = $api->getDetailUser();
        if ($user_ret['errcode'] != 0) {
            $this->addError('user', $user_ret['errmsg']);
            return false;
        }
        if (empty($user_ret['userlist'])) {
            return true;
        }
        $user_data = $user_ret['userlist'];

        $insert_data = array();
        foreach ($user_data as $user_info) {
            $insert_data[] = array(
                'userid' => $user_info['userid'],
                'name' => $user_info['name'],
                'position' => $user_info['position'],
                'mobile' => $user_info['mobile'],
                'gender' => $user_info['gender'],
                'email' => $user_info['email'],
                'avatar' => $user_info['avatar'],
                'status' => $user_info['status'],
                'enable' => $user_info['enable'],
                'extattr' => json_encode($user_info['extattr']),
                'department' => json_encode($user_info['department']),
                'order' => json_encode($user_info['order']),
            );
        }

        $transaction = $this->getDbConnection()->beginTransaction();
        $ret = $this->getDbConnection()->createCommand()->truncateTable('user');
        if ($ret === false) {
            $transaction->rollback();
            $this->addError('user', '数据清除失败');
            return false;
        }
        $ret = $this->getDbConnection()->schema->commandBuilder
            ->createMultipleInsertCommand('user', $insert_data)
            ->execute();
        if ($ret === false) {
            $transaction->rollback();
            $this->addError('user', '插入失败');
            return false;
        }
        $transaction->commit();
        return true;
    }
}
